<template>
	<view class="pagebox flex-column">
		<view class="userbox flex-row-center">
			<image class="head mr10" :src="`../static/${obj.u.type=='user'?8:7}.png`" mode="aspectFill"></image>
			<view class="name">{{obj.u.name}}</view>
			<view class="flex1"></view>
			<image class="seticon" src="../static/6.png" mode="aspectFill" @click="set"></image>
		</view>
		<view class="flex1 overflow-y pd30">
			<view class="card pd20" v-for="(v,i) in obj.list" :key="i">
				<view class="protitle mb10">{{v.name}}</view>
				<view class="flex-row ju-between">
					<text class="dept" v-if="v.depts">所属部门：{{v.depts?v.depts.join(','):''}}</text>
					<text class="dept" v-if="v.intime">创建时间：{{v.intime}}</text>
					<text class="dept">{{v.type}}</text>
				</view>
				<template v-if="v.detail&&v.detail.length">
					<FileTree :trees="v.detail" :index="i" :level="1" :filepath="''" :depts="v.depts" :project="v" @labelChange="handleChange" />
				</template>
			</view>
			<view v-if="!obj.list.length" class="nodata flex-center">--暂无项目信息--</view>
		</view>
		
<!-- 		<view class="" @click="chooseImage">拍照</view>
		<canvas v-if="obj.waterMarkParams.display" canvas-id="waterMarkCanvas" :style="canvasStyle"/> -->
		
		<view v-if="obj.showpass" class="editpass flex-center" @click="obj.showpass = false">
			<view class="card pd30 flex-column-center" @click.stop="()=>{}">
				<view class="w100 flex-row ju-between mb40">
					<text class="title">修改密码</text>
					<image @click="obj.showpass = false" class="cancel" src="../static/9.png" mode="aspectFill"></image>
				</view>
				<div class="inputbox flex-row-center mb20">
					<input class="input flex1 ml30 flex-row-center" type="text" maxlength="10" placeholder="请输入旧密码" placeholder-style="color:#c7c8c9;font-size:22rpx;" v-model="obj.editf.oldpass"/>
				</div>
				<div class="inputbox flex-row-center mb20">
					<input class="input flex1 ml30 flex-row-center" type="text" maxlength="10" placeholder="请输入新密码" placeholder-style="color:#c7c8c9;font-size:22rpx;" v-model="obj.editf.newpass"/>
				</div>
				<button class="button base-bg w-color" :disabled="obj.disabled" @click.stop="submitEdit">确认修改</button>
			</view>
		</view>
	</view>
</template>

<script setup>
    import { reactive, getCurrentInstance,onMounted,watch,computed,nextTick } from 'vue'
	import { onLoad,onShow,onTabItemTap,onReachBottom,onPullDownRefresh,onPageScroll } from '@dcloudio/uni-app';
	import FileTree from './FileTree.vue'
    let { proxy } = getCurrentInstance()
	let obj = reactive({
		list: [],
		waterMarkParams: {
			display: false, // 控制 canvas 创建与销毁
			canvasWidth: 300, // 默认宽度
			canvasHeight: 225, // 默认高度
			contentHeight: 150, // 将要被绘制到图像中的矩形的高度(px)
		},
		u: {},
		showpass: false,
		editf: {
			oldpass: '',
			newpass: ''
		},
		disabled: false,
	})
	
	onMounted(()=>{
		login()
	})
	
	onLoad(async(opt)=>{
	})
	
	onShow(async()=>{
	})
	
	const login=()=>{
		let lo = uni.getStorageSync('loginData')
		if(lo&&typeof lo == 'object'){
			if(lo.type=='mana'){
				const user = proxy.$c.getUser()
				obj.u = {
					...user,
					...lo
				}
				getlist()
			}else{
				proxy.$reQuest.post(lo.url,lo.f,{token: false},).then(async(res)=>{
					if(res.success){
						proxy.$c.setToken(res.msg.token);
						let user_ = proxy.$c.getUser()?JSON.parse(proxy.$c.getUser()):{};
						const user = {
							...user_,
							...res.msg,
							...lo
						}
						obj.u = user
						proxy.$c.setUser(JSON.stringify(user));
						setTimeout(()=>{
							getlist()
						},0)
					}
				}).catch(err=>{})	
			}
		}else{
			uni.reLaunch({
				url: '/pages/login'
			})
		}
	}
	
	const handleChange=(e)=>{
		obj.list[e[0]].detail[e[1]].hideTree = !obj.list[e[0]].detail[e[1]].hideTree
	}
	
	const getlist=()=>{
		proxy.$reQuest.post(obj.u.type=='user'?'mp/project/list':'manager/project/list',{company_id:0},{token:true}).then(res=>{
			if(res.success){
				obj.list = res.msg.list||[]
				if(obj.u.type=='mana'){
					obj.list.map(async(e)=>{
						e.depts = e.dept.map(ev=>{return ev.dept})
						e.detail = await getpro(e.project_id)
					})
				}else{
					obj.list.map(async(e)=>{
						e.depts = e.dept.map(ev=>{return ev.dept})
					})
				}
			}
		}).catch(err=>{})
	}
	
	const getpro=(project_id)=>{
		return new Promise((resovle,rej)=>{
			proxy.$reQuest.post('manager/project/get',{project_id:project_id},{token:true}).then(res=>{
				if(res.success&&res.msg.project&&res.msg.project.length&&res.msg.project[0].detail){
					resovle(JSON.parse(res.msg.project[0].detail))
				}else{resovle({})}
			}).catch(err=>{resovle({})})
		})
	}
	
	const set=()=>{
		uni.showActionSheet({
			itemList: ['退出登录', '修改密码'],
			success:(res)=>{
				if(res.tapIndex==0){
					uni.showModal({
						title: '提示',
						content: '确定要退出登录吗？',
						success:(res)=>{
							if (res.confirm) {
								uni.removeStorageSync('token')
								uni.removeStorageSync('loginData')
								uni.removeStorageSync('user')
								uni.reLaunch({url: '/pages/login'})		
							}
						}
					});
				}else{
					obj.showpass = true
				}
			}
		});
	}
	
	const submitEdit=(url,f)=>{
		if(!obj.editf.oldpass){
			proxy.$c.Toast('请输入旧密码！')
			return
		}
		if(!obj.editf.newpass){
			proxy.$c.Toast('请输入新密码！')
			return
		}
		if(obj.editf.oldpass===obj.editf.newpass){
			proxy.$c.Toast('新密码不能和旧密码相同！')
			return
		}
		obj.disabled = true
		proxy.$reQuest.post(obj.u.type=='user'?'mp/editpass':'manager/editpass',obj.editf,{token: true},).then(res=>{
				if(res.success){
					proxy.$c.Toast('修改成功,即将跳转登录！')
					setTimeout(()=>{
						uni.removeStorageSync('token')
						uni.removeStorageSync('loginData')
						uni.removeStorageSync('user')
						uni.reLaunch({url: '/pages/login'})	
					},2000)
				}else{
					obj.disabled = false
					proxy.$c.Toast(res.err);
				}
		}).catch(err=>{obj.disabled = false})
	}
	
	
	const canvasStyle = computed(()=>{  
		return {
			position: 'fixed', // 移除到屏幕外
			left: '9999px',
			width: obj.waterMarkParams.canvasWidth + 'px',
			height: obj.waterMarkParams.canvasHeight + 'px',
		} 
	})
	
	const findParents=(data, targetName)=>{
		let parents = [];
		const findRecursive=(node, level = 0)=>{
			if (node.name === targetName) {
				// let parent = node;//返回自己
				let parent = node.parent;//不返回自己
				while (parent) {
					// parents.unshift({ name: parent.name, level: level });//返回自己
					parents.unshift({ name: parent.name, level: level-1 });//不返回自己
					parent = parent.parent;
					level--;
				}
				return;
			}
			if (node.children) {
				for (let child of node.children) {
					child.parent = level==0?null:node;
					findRecursive(child, level + 1);
				}
			}
		}
		findRecursive({ children: data });
		return parents;
	}
	
	const chooseImage=()=>{
		uni.chooseImage({
		  sourceType: ['all'],
		  success: async ({ tempFilePaths, tempFiles }) => {
			// 这里就得到了带水印的图片路径列表
			 const imgFileArr = await callAddWaterMark(tempFilePaths)
		  }
		})
	}
	
	const callAddWaterMark=async(imgPathArr)=>{
		let results = []
		if(imgPathArr.length > 0) {
		  let idx = 0
		  while(idx < imgPathArr.length) {
			const tempFilePath = await addWaterMark(imgPathArr[idx],800)
			results.push(tempFilePath)
			idx = idx + 1
		  }
		}
		return results
	}
	
	// 添加水印
	const addWaterMark=(src,minWidth)=>{
		return new Promise((resolve, reject) => {
			// 获取图片信息，配置 canvas 尺寸
			uni.getImageInfo({
				src,
				success: async(res) => {
					// 修复部分手机(如红米9)手机屏幕比较窄拍摄出来的图片水印压缩着覆盖的问题
					obj.waterMarkParams.canvasWidth = Math.max(res.width, minWidth);
					obj.waterMarkParams.canvasHeight = res.width>=minWidth?res.height:res.height*(minWidth/res.width);
					obj.waterMarkParams.display = true
					console.log('当前图片信息waterMarkParams：', obj.waterMarkParams);
					
					// 等待 canvas 元素创建
					await nextTick()
					let context = uni.createCanvasContext("waterMarkCanvas");
					/* 绘制 */
					const { canvasWidth, canvasHeight, contentHeight } = obj.waterMarkParams
					// 绘制前清空画布
					context.clearRect(0, 0, canvasWidth, canvasHeight);
					// 将图片src放到cancas内，宽高必须为图片大小
					context.drawImage(src, 0, 0, canvasWidth, canvasHeight, canvasWidth, canvasHeight);
					// 设置边框的透明度
					context.setGlobalAlpha(0.3);
					context.beginPath();
					// 绘制底部的白色背景
					context.rect(0, canvasHeight - contentHeight, canvasWidth, contentHeight);
					context.setFillStyle("white");
					context.fill();
					// 设置文字的透明度
					context.setGlobalAlpha(1);
					// 3.绘制底部的文字
					context.setFontSize(32);
					context.setTextAlign("left");
					context.setFillStyle("black");
					context.fillText(`拍摄人：dejavu`, 50 , canvasHeight - 90 );
					context.fillText(`拍摄时间：2024-08-22`, 50, canvasHeight - 40);
					// 一定要加上一个定时器否则进入到页面第一次可能会无法正常拍照，后几次才正常
					setTimeout(() => {
						// 本次绘画完重开开始绘画，并且在绘画完毕之后再保存图片，不然页面可能会出现白屏等情况
						context.draw(false, () => {
							console.log('!!!!!开始绘画', canvasWidth, canvasHeight);
							uni.canvasToTempFilePath({
								canvasId: "waterMarkCanvas",
								fileType: "jpg",
								width: canvasWidth,
								height: canvasHeight,
								destWidth: canvasWidth,
								destHeight: canvasHeight,
								success: ({ tempFilePath }) => {
									console.log('绘制成功', tempFilePath);
									obj.waterMarkParams.display = false
									resolve(tempFilePath)
								},
								fail: err => {
									reject(err)
									console.log(err);
								}
							})
						})
					}, 1000);
				}
			})
		})
	}

</script>

<style lang="scss" scoped>
	.pagebox{
		width: 100vw;height: 100vh;overflow: hidden;
		background: #f0f0f0;
		.userbox{
			width: 100vw;height: auto;background: #fff;padding: 20rpx 40rpx;box-sizing: border-box;
			.head{width: 60rpx;height: 60rpx;border-radius: 60rpx;}
			.name{font-size: 26rpx;}
			.seticon{width: 30rpx;height: 30rpx;opacity: 0.6;}
		}
		.nodata{width: 100%;height: 100%;font-size: 22rpx;color: #999;}
		.card{
			width: 100%;height: auto;border-radius: 10rpx;background: #fff;margin-bottom: 30rpx;
			.protitle{font-size: 32rpx;font-weight: bold;}
			.dept{font-size: 24rpx;color: #999;}
		}
		.editpass{
			position: fixed;width: 100vw;height: 100vh;background: rgba(0,0,0,0.6);border-radius: 10rpx;padding: 50rpx;box-sizing: border-box;z-index: 99999999;
			left: 0;top: 0;
			.title{font-size: 32rpx;}
			.cancel{width: 40rpx;height: 40rpx;}
			.button{
				width: 100%;height: 100rpx;border-radius: 100rpx;text-align: center;line-height: 100rpx;font-size: 26rpx;
			}
			.inputbox{
				width: 100%;height: 100rpx;border-radius: 100rpx;background: #f0f0f0;font-size: 26rpx;
			}
		}
	}
</style>
